<template>
  <div class="anypay-apple-list-page">
    <div class="anypay-apple-page-header">
      <h1>支付产品管理</h1>
      <p>管理平台支持的支付产品类型，配置产品参数</p>
    </div>

    <!-- 搜索区域 -->
    <div class="anypay-apple-card anypay-apple-mb-6">
      <a-card>
        <div class="search-container standard">
          <!-- 产品名称 -->
          <div class="search-field">
            <label class="search-label">产品名称:</label>
            <a-input
              v-model:value="searchForm.productName"
              placeholder="请输入产品名称"
              class="search-input"
              allowClear
              @press-enter="handleSearch"
            />
          </div>

          <!-- 产品类型 -->
          <div class="search-field">
            <label class="search-label">产品类型:</label>
            <a-select
              v-model:value="searchForm.productType"
              placeholder="请选择产品类型"
              class="search-select-large"
              allowClear
            >
              <a-select-option value="NATIVE">扫码支付</a-select-option>
              <a-select-option value="APP">APP支付</a-select-option>
              <a-select-option value="JSAPI">小程序支付</a-select-option>
              <a-select-option value="H5">H5支付</a-select-option>
              <a-select-option value="CARD">刷卡支付</a-select-option>
            </a-select>
          </div>

          <!-- 状态 -->
          <div class="search-field">
            <label class="search-label">状态:</label>
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              class="search-select"
              allowClear
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </div>

          <!-- 操作按钮 -->
          <div class="search-actions">
            <a-button type="primary" @click="handleSearch" class="search-btn">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="search-btn">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="anypay-apple-card">
      <a-card>
        <div class="anypay-apple-table anypay-apple-toolbar">
          <AnyTable
            ref="productTable"
            :autoLoad="true"
            :dataLoader="loadProductData"
            :tableColumns="tableColumns"
            :searchParams="searchParams"
            :tableScroll="{ x: 'max-content' }"
            tableRowKey="productId"
            @loadComplete="handleLoadComplete"
          >
            <template #tableToolbar>
              <a-space :size="12">
                <a-button type="primary" @click="handleCreate">
                  <PlusOutlined /> 新增产品
                </a-button>
              </a-space>
            </template>
              <template #tableCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getProductStatusColor(record.status)">
                  {{ getProductStatusName(record.status) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'productType'">
                <a-tag :color="getProductTypeColor(record.productType)">
                  {{ getProductTypeName(record.productType) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'amountRange'">
                <span style="color: #1890ff;">
                  ¥{{ record.minAmount }} ~ ¥{{ formatAmount(record.maxAmount) }}
                </span>
              </template>
              <template v-else-if="column.key === 'action'">
                <div class="anypay-apple-actions">
                  <a-space>
                    <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                    <a-dropdown placement="bottomRight">
                      <a-button type="link" size="small">
                        <MoreOutlined />
                        更多
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item
                            key="toggle"
                            @click="handleToggleStatus(record)"
                            :disabled="record.status === ProductStatus.DEPRECATED"
                          >
                            {{ record.status === ProductStatus.ENABLED ? '禁用' : '启用' }}
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item key="delete" @click="handleDelete(record)" style="color: #ff4d4f;">
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </div>
              </template>
            </template>
          </AnyTable>
        </div>
      </a-card>
    </div>

    <!-- 新增/编辑产品对话框 -->
    <a-modal
      v-model:open="showProductDialog"
      :title="productDialogTitle"
      width="700px"
      @ok="handleSaveProduct"
      @cancel="handleCancelProduct"
    >
      <a-form
        :model="productForm"
        :rules="productRules"
        ref="productFormRef"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="产品名称" name="productName">
              <a-input v-model:value="productForm.productName" placeholder="请输入产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="产品代码" name="productCode">
              <a-input v-model:value="productForm.productCode" placeholder="请输入产品代码" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="产品类型" name="productType">
              <a-select v-model:value="productForm.productType" placeholder="请选择产品类型">
                <a-select-option value="NATIVE">扫码支付</a-select-option>
                <a-select-option value="APP">APP支付</a-select-option>
                <a-select-option value="JSAPI">小程序支付</a-select-option>
                <a-select-option value="H5">H5支付</a-select-option>
                <a-select-option value="CARD">刷卡支付</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="productForm.status">
                <a-select-option :value="ProductStatus.ENABLED">启用</a-select-option>
                <a-select-option :value="ProductStatus.DISABLED">禁用</a-select-option>
                <a-select-option :value="ProductStatus.TESTING">测试中</a-select-option>
                <a-select-option :value="ProductStatus.MAINTENANCE">维护中</a-select-option>
                <a-select-option :value="ProductStatus.DEPRECATED">已废弃</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="产品描述" name="productDesc">
          <a-textarea v-model:value="productForm.productDesc" placeholder="请输入产品描述" :rows="3" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="最小金额" name="minAmount">
              <a-input-number
                v-model:value="productForm.minAmount"
                placeholder="请输入最小金额"
                :min="0.01"
                :precision="2"
                style="width: 100%;"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最大金额" name="maxAmount">
              <a-input-number
                v-model:value="productForm.maxAmount"
                placeholder="请输入最大金额"
                :min="0.01"
                :precision="2"
                style="width: 100%;"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, MoreOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import {
  paymentProducts,
  ProductStatus,
  getProductStatusName,
  getProductStatusColor,
  getProductTypeName,
  getProductTypeColor,
  type PaymentProduct
} from '@/mock'
import AnyTable from '@/components/AnyTable.vue'

// 响应式数据
const showProductDialog = ref(false)

// 组件引用
const productTable = ref()

// 表单数据
const searchForm = reactive({
  productName: '',
  productType: undefined,
  status: undefined
})

// 搜索参数
const searchParams = reactive<{
  productName?: string
  productType?: string
  status?: number
}>({})

const productForm = reactive({
  productId: '',
  productName: '',
  productCode: '',
  productType: '',
  productDesc: '',
  minAmount: 0.01,
  maxAmount: 50000,
  status: ProductStatus.ENABLED
})

// 分页配置已由 AnyTable 内部处理

// 表格列定义
const tableColumns = [
  {
    title: '产品名称',
    dataIndex: 'productName',
    key: 'productName',
    width: 150
  },
  {
    title: '产品代码',
    dataIndex: 'productCode',
    key: 'productCode',
    width: 120
  },
  {
    title: '产品类型',
    key: 'productType',
    width: 100,
    align: 'center'
  },
  {
    title: '金额范围',
    key: 'amountRange',
    width: 150,
    align: 'center',
    visible: false
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center',
    visible: false
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 150,
    visible: false
  },
  {
    title: '操作',
    key: 'action',
    width: 220,
    align: 'center'
  }
]

// 表单验证规则
const productRules = {
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  productCode: [
    { required: true, message: '请输入产品代码', trigger: 'blur' }
  ],
  productType: [
    { required: true, message: '请选择产品类型', trigger: 'change' }
  ],
  minAmount: [
    { required: true, message: '请输入最小金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '最小金额必须大于0', trigger: 'blur' }
  ],
  maxAmount: [
    { required: true, message: '请输入最大金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '最大金额必须大于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const productDialogTitle = computed(() => {
  return productForm.productId ? '编辑产品' : '新增产品'
})

// 数据加载函数
const loadProductData = async (params: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    let filteredData = [...paymentProducts]

    // 应用搜索筛选
    if (params.productName) {
      filteredData = filteredData.filter(item =>
        item.productName.toLowerCase().includes(params.productName.toLowerCase())
      )
    }

    if (params.productType) {
      filteredData = filteredData.filter(item => item.productType === params.productType)
    }

    if (params.status !== undefined) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }

    // 计算分页
    const startIndex = ((params.pageNumber || 1) - 1) * (params.pageSize || 10)
    const endIndex = startIndex + (params.pageSize || 10)
    const records = filteredData.slice(startIndex, endIndex)

    return {
      records,
      total: filteredData.length,
      pageNumber: params.pageNumber || 1,
      pageSize: params.pageSize || 10
    }
  } catch (error) {
    console.error('Failed to load product data:', error)
    return { records: [], total: 0, pageNumber: 1, pageSize: 10 }
  }
}

// 加载完成回调
const handleLoadComplete = () => {
  console.log('Product data loaded successfully')
}

// 方法
const handleCreate = () => {
  resetProductForm()
  showProductDialog.value = true
}

const handleEdit = (record: PaymentProduct) => {
  Object.assign(productForm, record)
  showProductDialog.value = true
}

const handleDelete = (record: PaymentProduct) => {
  message.success(`删除产品 ${record.productName} 成功`)
  searchProducts()
}

const handleToggleStatus = (record: PaymentProduct) => {
  const newStatus = record.status === ProductStatus.ENABLED ? ProductStatus.DISABLED : ProductStatus.ENABLED
  const action = newStatus === ProductStatus.ENABLED ? '启用' : '禁用'

  record.status = newStatus
  message.success(`${action}产品成功`)
}

const handleSearch = () => {
  // 清空之前的搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  // 只添加非空的搜索条件
  if (searchForm.productName) {
    searchParams.productName = searchForm.productName
  }
  if (searchForm.productType) {
    searchParams.productType = searchForm.productType
  }
  if (searchForm.status !== undefined) {
    searchParams.status = searchForm.status
  }

  searchProducts()
}

const handleReset = () => {
  // 清空搜索表单
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = key === 'status' || key === 'productType' ? undefined : ''
  })

  // 清空搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  searchProducts()
}

// 搜索和重置
const searchProducts = () => {
  productTable.value?.refreshTable(true)
}

// handleTableChange 已由 AnyTable 内部处理，不再需要

const handleSaveProduct = async () => {
  try {
    // 验证最大金额必须大于最小金额
    if (productForm.maxAmount <= productForm.minAmount) {
      message.error('最大金额必须大于最小金额')
      return
    }

    if (productForm.productId) {
      message.success('编辑产品成功')
    } else {
      productForm.productId = generateProductId()
      message.success('新增产品成功')
    }
    showProductDialog.value = false
    searchProducts()
  } catch (error) {
    message.error('保存失败')
  }
}

const handleCancelProduct = () => {
  showProductDialog.value = false
  resetProductForm()
}

const resetProductForm = () => {
  Object.assign(productForm, {
    productId: '',
    productName: '',
    productCode: '',
    productType: '',
    productDesc: '',
    minAmount: 0.01,
    maxAmount: 50000,
    status: ProductStatus.ENABLED
  })
}

const generateProductId = () => {
  return 'PROD' + Date.now().toString().slice(-6)
}

const formatAmount = (amount: number) => {
  return amount.toLocaleString()
}

// loadData 和 onMounted 已由 AnyTable 的 autoLoad 处理
</script>

<style scoped>
@import '../common/list-page.css';

/* 对话框样式 */
.ant-modal .ant-modal-body {
  padding: 20px;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}
</style>